package edu.bluebeanforum.controller;

import edu.bluebeanforum.common.AppResult;
import edu.bluebeanforum.common.ResultCode;
import edu.bluebeanforum.config.AppConfig;
import edu.bluebeanforum.model.Article;
import edu.bluebeanforum.model.Board;
import edu.bluebeanforum.model.User;
import edu.bluebeanforum.service.IArticleService;
import edu.bluebeanforum.service.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;


@Api(tags = "帖子接口")
@RestController
@RequestMapping("/article")
@Slf4j
public class ArticleController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IBoardService boardService;

    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("板块id") @RequestParam("boardId") @NonNull Long boardId,
                            //@RequestParam 从请求中获取该参数值，@ApiParam 对参数进行描述，@NotNull 保证参数不为 null
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {
        //校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        //板块的校验
        Board board = boardService.selectById(boardId.longValue());
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.fail(ResultCode.FAILED_BOARD_BANNED);
        }
        //封装文章对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        articleService.create(article);


        return AppResult.success();
    }

    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块id") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> articles;
        if (boardId == null) {
//        查询所有的
            articles = articleService.selectAll();
        } else {
            articles = articleService.selectAllByBoardId(boardId);
        }
        if (articles == null) {
//            如果结合集可空，那么创建一个空集合
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }

    @ApiOperation("根据id查询帖子详情")
    @GetMapping("/details")
    public AppResult getDeatils(HttpServletRequest request,
                                @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
//        获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
//        调用service层，获取帖子详情
        Article article = articleService.selectDetailById(id);
//        判断当前用户是否是作者
        if (user.getId() == article.getUserId()) {
//            标识为作者，显示编辑和删除按钮
            article.setOwn(true);
        }
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子")
    @GetMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子内容") @RequestParam("content") @NonNull String content) {
//        获取当前用户是否是作者
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
//        查询帖子详情
        Article article = articleService.selectById(id);
        if (article == null) {
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
//       判断用户是否是作者
        if (user.getId() != article.getUserId()) {
            return AppResult.fail(ResultCode.FAILED_USER_ARTICLE_COUNT);
        }
        articleService.modify(id, title, content);
        log.info("帖子更新成功");
        return AppResult.success();
    }


    @ApiOperation("点赞帖子")
    @PostMapping("/thumbsUpById")
    public AppResult thumbsUpById(HttpServletRequest request,
                                  @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
//      校验用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
//        判断用户是否被禁言
        if (user.getState() == 1) {
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult delete(HttpServletRequest request,
                                  @ApiParam("帖子id") @RequestParam("id") @NonNull Long id) {
//      校验用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
//        判断用户是否被禁言
        if (user.getState() == 1) {
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
//       查询帖子详情
        Article article=articleService.selectById(id);
        if(article==null){
            return AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
//        校验当前登录用户是否是作者  只有是作者才可以删除
        if (user.getId()!=article.getUserId()) {
            return AppResult.fail(ResultCode.FAILED_FORBIDDEN);
        }
        articleService.deleteById(id);
        return AppResult.success();
    }



    @ApiOperation("获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                   @ApiParam("用户id") @RequestParam(value = "userId" ,required = false) Long userId){

        //如果userId为空，则从session中获得当前登录用户的id
        if(userId==null){
            HttpSession session = request.getSession(false);
            User user= (User) session.getAttribute(AppConfig.USER_SESSION);
            userId=user.getId();
        }
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }
}
